package com.itheima.cs;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.itheima.cs.R;
import com.itheima.cs.dao.UserDao;
import com.itheima.cs.entity.Userinfo;
import com.itheima.cs.utils.CommonUtils;
import com.itheima.cs.utils.LoginManager;
import com.sunmi.printerx.PrinterSdk;
import com.sunmi.printerx.SdkException;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.*;

import java.io.IOException;
import java.util.List;


public class MainActivity extends AppCompatActivity {

    private EditText usernameEditText;
    private EditText passwordEditText;

    private CheckBox cbRemember;
    private ProgressDialog progressDialog;
    private UserDao dao;
    private TextView tvChangePassword;

    private Handler mainHandler;
    private SharedPreferences sharedPreferences;

    private static final String PREF_NAME = "login_preferences";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_PASSWORD = "password";
    private static final String KEY_REMEMBER="remember";

    /**
     * 指定操作的商米打印机设备
     */
//    public PrinterSdk.Printer selectPrinter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        usernameEditText = findViewById(R.id.et_username);
        passwordEditText = findViewById(R.id.et_password);
        cbRemember = findViewById(R.id.cb_remember);

        dao = new UserDao();

        mainHandler = new Handler(getMainLooper());

        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("登录中...");
        progressDialog.setCancelable(false);

//        sharedPreferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
//        String savedUsername = sharedPreferences.getString(KEY_USERNAME, "");
//        usernameEditText.setText(savedUsername);
        //test commit

        // 加载上次保存的记住密码状态
        loadRememberState();

        findViewById(R.id.btn_login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String model = Build.MODEL; // 获取设备型号
                if (model.startsWith("CT58")){
                    //扫码机器优博讯CT58
                    boolean checkWifi = CommonUtils.checkWifiInfo(MainActivity.this);
                    if (!checkWifi) {
                        //优博讯CT58需要检验WiFi，不是TSZG开头的wifi
                        String errorMessage = "设备连接得无线网不正确，请连接正确的热点（热点名称以TSZG开头）。";
                        Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

                final String username = usernameEditText.getText().toString();
                final String password = passwordEditText.getText().toString();

                if (TextUtils.isEmpty(username)) {
                    CommonUtils.showShortMsg(MainActivity.this, "请输入用户名");
                    usernameEditText.requestFocus();
                } else if (TextUtils.isEmpty(password)) {
                    CommonUtils.showShortMsg(MainActivity.this, "请输入用户密码");
                    passwordEditText.requestFocus();
                } else {
                    progressDialog.show();

                    final Handler timeoutHandler = new Handler();
                    timeoutHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            progressDialog.dismiss();
                            CommonUtils.showShortMsg(MainActivity.this, "登录超时，请检查网络是否正确");
                        }
                    }, 5000);

                    LoginManager.getInstance(MainActivity.this).login(username, password, null,new LoginManager.LoginCallback() {
                        @Override
                        public void onSuccess() {

                            timeoutHandler.removeCallbacksAndMessages(null);
                            progressDialog.dismiss();
                            mainHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                                }
                            });

                            LoginManager.getInstance(MainActivity.this).saveCredentials(username, password);

//                            SharedPreferences.Editor editor = sharedPreferences.edit();
//                            editor.putString(KEY_USERNAME, username);
//                            editor.apply();
                            // 如果勾选了记住密码，则保存
                            if (cbRemember.isChecked()) {
                                saveLoginInfo(username, password);
                            } else {
                                clearLoginInfo();
                            }
                            // 保存记住密码的勾选状态
                            saveRememberState(cbRemember.isChecked());

                            Intent intent = new Intent(MainActivity.this, HomeFragmentActivity.class);
                            startActivity(intent);
                            finish();
                        }

                        @Override
                        public void onFailure(String errorMessage) {

                            timeoutHandler.removeCallbacksAndMessages(null);
                            progressDialog.dismiss();
                            mainHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    CommonUtils.showShortMsg(MainActivity.this, errorMessage);
                                }
                            });

                        }
                    });
                }
            }
        });

        tvChangePassword = findViewById(R.id.tv_change_password);
        tvChangePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, ChangePasswordActivity.class);
                startActivity(intent);
            }
        });

//        initPrinter();
    }

    private void saveLoginInfo(String username, String password) {
        SharedPreferences sharedPreferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(KEY_USERNAME, username);
        editor.putString(KEY_PASSWORD, password);
        editor.apply();
    }

    private void loadLastLoginInfo() {
        SharedPreferences sharedPreferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
        boolean remember = sharedPreferences.getBoolean(KEY_REMEMBER, false);

        if (remember) {
            String lastUsername = sharedPreferences.getString(KEY_USERNAME, "");
            String lastPassword = sharedPreferences.getString(KEY_PASSWORD, "");
            usernameEditText.setText(lastUsername);
            passwordEditText.setText(lastPassword);
            cbRemember.setChecked(true);
        }
    }

    private void clearLoginInfo() {
        SharedPreferences sharedPreferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove(KEY_USERNAME);
        editor.remove(KEY_PASSWORD);
        editor.apply();
    }

    private void saveRememberState(boolean remember) {
        SharedPreferences sharedPreferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean(KEY_REMEMBER, remember);
        editor.apply();
    }

    private void loadRememberState() {
        SharedPreferences sharedPreferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
        boolean remember = sharedPreferences.getBoolean(KEY_REMEMBER, false);
        cbRemember.setChecked(remember);
        if (remember) {
            loadLastLoginInfo();
        }
    }

//    private void initPrinter() {
//        try {
//            PrinterSdk.getInstance().getPrinter(this, new PrinterSdk.PrinterListen() {
//                @Override
//                public void onDefPrinter(PrinterSdk.Printer printer) {
//                    selectPrinter = printer;
//                }
//
//                @Override
//                public void onPrinters(List<PrinterSdk.Printer> printers) {
//
//                }
//            });
//        } catch (SdkException e) {
//            e.printStackTrace();
//        }
//    }
//
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        PrinterSdk.getInstance().destroy();
//    }


}


